﻿package pete.forms {

import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.Sprite;
import flash.events.Event;
import flash.net.URLRequest;



public class Pattern extends Sprite {
	
	// Properties
	// -----------------------------------------------------------
	
	private var _tile:BitmapData;
	private var _width:Number;
	private var _height:Number;
	
	
	
	
	// Constructor
	// -----------------------------------------------------------
	
	public function Pattern($width:Number = 100, $height:Number = 100) {
		
		setSize($width, $height);
	}
	
	
	
	// Public Functions
	// -----------------------------------------------------------
	
	public function setSize($width:Number, $height:Number):void {
		
		_width = $width;
		_height = $height;
	}
	
	public function resize($width:Number, $height:Number):void {
		
		setSize($width, $height);
		build();
	}
	
	public function draw($object:Object):void {
		
		if ($object is String) {
			
			load($object as String);
		}
		else if ($object is BitmapData) {
			
			_tile = ($object as BitmapData);
			build();
		}
	}
	
	
	
	// Private Functions
	// -----------------------------------------------------------
	
	private function load($url:String):void {
		
		var loader:Loader = new Loader();
		loader.load(new URLRequest($url));
		loader.contentLoaderInfo.addEventListener(Event.COMPLETE, tileTexture);
	}
	
	private function build():void {
		
		if (_tile) {
			graphics.beginBitmapFill(_tile);
			graphics.drawRect(0, 0, _width, _height);
		}
	}
	
	
	
	// Event Handlers
	// -----------------------------------------------------------
	
	private function tileTexture(e:Event):void {
		
		_tile = e.target.content.bitmapData;
		build();
	}
	
	
}
}